<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <div class="filter-item">
        <el-button
          v-if="can('permission.role.create')"
          type="primary"
          icon="el-icon-edit"
          @click="showAddDialog()"
        >新增角色
        </el-button>
      </div>
    </div>
    <el-table v-loading="loading" :data="items" stripe style="width: 100%">
      <el-table-column prop="id" type="index" class-name="text-center" />
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="created_at" label="创建时间" width="200" />
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="{row}">
          <el-button v-if="can('permission.role.edit')" type="primary" plain size="mini" @click="showAddDialog(row)">
            编辑
          </el-button>
          <el-button v-if="can('permission.role.delete') && $store.state.user.ln_role_id !== row.id" type="danger" plain size="mini" @click="deleteItem(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="editDialog.visible" class="dialog-box" title="创建角色">
      <el-form :model="editDialog.row" label-width="60px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editDialog.row.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editDialog.row.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-tree
            v-loading="editDialog.permissionLoading"
            :data="editDialog.permissions"
            :props="editDialog.permissionProps"
            :default-checked-keys="editDialog.row.tempPermissions"
            show-checkbox
            node-key="id"
            @check="checkPermissions"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { deleteRole, getRoles, getPermissions, addRole } from '@/api/role'

const defaultForm = {
  // 真实选中的权限
  selectedPermissions: ['dashboard', 'overview'],
  // 控件渲染时使用的权限值
  tempPermissions: ['dashboard', 'overview']
}

export default {
  name: 'Role',
  data() {
    return {
      loading: false,
      items: [],
      editDialog: {
        // 配置内容
        visible: false,
        defaultData: defaultForm,
        status: 'create',
        submitLoading: false,
        row: { },
        rules: {
          name: { required: true, message: '请输入名称', trigger: 'blur' }
        },
        // 角色业务代码
        permissionLoading: false,
        permissions: [],
        permissionProps: {
          children: 'children',
          label: 'name'
        }
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取角色列表
    getList() {
      this.loading = true
      getRoles().then(response => {
        this.items = response.data
      }).finally(() => {
        this.loading = false
      })
    },
    // 获取权限例表
    getPermissions() {
      this.editDialog.permissionLoading = true
      getPermissions().then(response => {
        this.editDialog.permissions = response.data
      }).finally(() => {
        this.editDialog.permissionLoading = false
      })
    },
    // 显示新增窗口
    showAddDialog(row) {
      this.getPermissions()
      this.editDialog.visible = true
      if (!row) {
        this.editDialog.status = 'create'
      } else {
        this.editDialog.status = 'update'
        this.editDialog.row = this._.cloneDeep(row)
        this.editDialog.row.selectedPermissions = this._.map(row.permissions, permission => {
          return permission.split('.').join('_')
        })
        this.editDialog.row.tempPermissions = this._.cloneDeep(this.editDialog.row.selectedPermissions)
        this.editDialog.row.tempPermissions = this._.filter(this.editDialog.row.tempPermissions, permission => {
          let checked = true
          this._(this.editDialog.row.tempPermissions).forEach(tempPermission => {
            if (tempPermission.indexOf(permission) >= 0 && tempPermission !== permission) {
              checked = false
            }
          })
          return checked
        })
      }
    },
    deleteItem(item) {
      this.$messageBox.confirm(`确定要删除 ${item.name} 吗?`, '删除', () => {
        deleteRole(item.id).then(() => {
          this.$notice.success('删除成功')
        }).finally(() => {
          this.getList()
        })
      }, () => {})
    },
    // 提交表单
    submitForm() {
      this.editDialog.row.permissions = this._.map(this.editDialog.row.selectedPermissions, permission => {
        return permission.split('_').join('.')
      })
      addRole(this.editDialog.row).then(() => {
        this.$notice.success()
      }, error => {
        this.$notice.error(error)
      }).finally(() => {
        this.editDialog.submitLoading = false
        this.editDialog.visible = false
        this.getList()
      })
    },
    // 选中权限
    checkPermissions(currentChecked, allCheckInfo) {
      this.editDialog.row.selectedPermissions = allCheckInfo.checkedKeys.concat(allCheckInfo.halfCheckedKeys)
    }
  }
}
</script>
<style lang="scss" scoped>
  .dialog-box {
    .el-form {
      padding-right: 30px;
    }
    /deep/ .el-dialog {
      .el-tree {
        height: 200px;
        overflow-y: auto;
      }
      .el-dialog__body {
        padding-bottom: 0;
      }
    }
  }
</style>
